package nan.demo2.model;

import javax.swing.*;
import java.sql.*;

public class DBtest {

    String name;
    String pass;

     public void setInfo(String username,String password){
       this.name=username;
       this.pass=password;
    }


    public User userLogin() {
        String url = "jdbc:mysql://localhost:3306/library_management?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
        String username = "root"; // 你的数据库用户名
        String password = "060625nan"; // 你的数据库密码
        String sql="select * from user where username=? and password=?";

        User user=null;

        Connection conn=null;
        PreparedStatement prep=null;
        ResultSet rs=null;

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
             conn=DriverManager.getConnection(url, username, password);



            //数据查询
             prep = conn.prepareStatement(sql);
            prep.setString(1,name);
            prep.setString(2,pass);


            //数据结果集
             rs = prep.executeQuery();

            while (rs.next()) {
                 user = new User();
                 user.setId(rs.getInt("id"));
                 user.setUsername(rs.getString("username"));
                 user.setPassword(rs.getString("password"));
                 user.setName(rs.getString("name"));
                 user.setRole(rs.getString("role"));
                 user.setEmail(rs.getString("email"));
                 user.setPhone(rs.getString("phone"));
                 user.setCreateTime(
                         rs.getTimestamp("create_Time").toLocalDateTime()
                 );
                 user.setStatus(rs.getInt("status"));
            }
            return user;


        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }catch (SQLException e){
            throw new RuntimeException(e);
        }finally {
            try {
                rs.close();
            } catch (SQLException e) {
                System.out.println("rs");
                throw new RuntimeException(e);
            }
            try {
                prep.close();
            } catch (SQLException e) {
                System.out.println("prep");
                throw new RuntimeException(e);
            }
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println("conn");
                throw new RuntimeException(e);
            }
        }



    }
}
